package com.purchase.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.purchase.entity.Coupon;
import com.purchase.entity.Goods;
import com.purchase.entity.GoodsStock;
import com.purchase.entity.WxUser;
import com.purchase.mapper.*;
import com.purchase.service.OrderService;
import com.purchase.util.LogInfo;
import com.purchase.util.OrderIdGenerater;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private CartMapper cartMapper;

	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private GoodsStockMapper goodsStockMapper;

	@Autowired
	private CouponMapper couponMapper;
	
//	@Autowired
//	MemberCouponsMapper memberCouponsMapper;
	
	@Autowired
	WxUserMapper wxUserMapper;
	
	@Override
	public ResponseForm getOrderListByStatus(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String wxUid = null;
		try {
			wxUid = (String) paramMap.get("wxUid");
			if (!StringUtils.isNotBlank(wxUid)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			// 获取订单列表
			com.purchase.util.Page.parsePage(paramMap);
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			List<Map<String, Object>> list = orderMapper.getOrderByStatus(paramMap);
			for (Map<String, Object> map : list) {
				List<Map<String, Object>> details = orderMapper
						.getOrderDetailListByOrderId(String.valueOf(map.get("id")));
				map.put("details", details);

				// 如果有关联优惠券则显示优惠金额
				Coupon coupon = couponMapper.getCouponByOrderId(String.valueOf(map.get("id")));
				if (coupon != null) {
					map.put("couponId", coupon.getId());
					map.put("couponAmount", coupon.getCouponAmount());
				}
			}
			result.setData(list);
			result.setTotal((int) pageHelper.getTotal());
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取订单列表error,wxUid=" + wxUid, e);
		}
		return result;
	}

	@Override
	public ResponseForm getOrderDetailList(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			String storeNo = (String) paramMap.get("storeNo");
			if (!StringUtils.isNotBlank(orderId) || !StringUtils.isNotBlank(storeNo)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			// 返回订单详情列表
			List<Map<String, Object>> list = orderMapper.getOrderDetailListByOrderId(orderId);

			// 订单信息
			Map<String, Object> order = orderMapper.getOrderByIdAndStoreNo(orderId, storeNo);
			HashMap<String, Object> dataMap = new HashMap<>();
			dataMap.put("list", list);
			dataMap.put("orderId", String.valueOf(order.get("id")));
			dataMap.put("wxUid", String.valueOf(order.get("wx_uid")));
			dataMap.put("orderPrice", String.valueOf(order.get("price")));
			dataMap.put("orderGoodsNum", String.valueOf(order.get("goods_num")));
			dataMap.put("createTime", t2d((Timestamp) order.get("create_time")));
			dataMap.put("updateTime", t2d((Timestamp) order.get("update_time")));
			dataMap.put("orderStatus", String.valueOf(order.get("order_status")));
			dataMap.put("logisticStatus", String.valueOf(order.get("logistic_status")));
			dataMap.put("postage", String.valueOf(order.get("postage")));
			dataMap.put("userAddressId",
					String.valueOf(order.get("user_address_id") == null ? "" : order.get("user_address_id")));
			dataMap.put("contacts", String.valueOf(order.get("contacts")));
			dataMap.put("mobilePhone", String.valueOf(order.get("mobile_phone")));
			dataMap.put("detailedAddress", String.valueOf(order.get("detailed_address")));
			dataMap.put("expireTime", String.valueOf(order.get("expire_time")));
			dataMap.put("activityId", String.valueOf(order.get("activity_id")));
			dataMap.put("activityName", String.valueOf(order.get("activity_name")));
			dataMap.put("tradeType", String.valueOf(order.get("trade_type")));
			dataMap.put("orderType", String.valueOf(order.get("order_type")));
			dataMap.put("logisticsName", String.valueOf(order.get("logistics_name")));
			dataMap.put("logisticsNo", String.valueOf(order.get("logistics_no")));
			dataMap.put("remark", String.valueOf(order.get("remark")));
			// 加入本活动有效优惠券
			List<Coupon> couponList = couponMapper.getMyCouponListUnused(dataMap);
			if (couponList.size() > 0) {
				dataMap.put("couponFlag", 1);
			} else {
				dataMap.put("couponFlag", 0);
			}
			// 如果有关联优惠券则显示优惠金额
			Coupon coupon = couponMapper.getCouponByOrderId(orderId);
			if (coupon != null) {
				dataMap.put("couponId", coupon.getId());
				dataMap.put("couponAmount", coupon.getCouponAmount());
			}
			result.setData(dataMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取订单详情列表error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm updateOrderIsDelete(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			if (!StringUtils.isNotBlank(orderId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			
//			/*会员优惠 如果取消订单优惠返回*/
			orderMapper.updateOrderIsDeleteByOrderId(paramMap);
//			Order order = orderMapper.selectByPrimaryKey(orderId);
//			if(order.get.getOrderStatus()=="W") {
//				
//			}
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("删除订单error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm updateOrderAddress(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			String userAddressId = (String) paramMap.get("userAddressId");
			if (!StringUtils.isNotBlank(orderId) || !StringUtils.isNotBlank(userAddressId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			orderMapper.updateOrderAddress(paramMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("更新订单关联地址error,orderId=" + orderId, e);
		}
		return result;
	}

	/**
	 * 1. 购物车内商品 -> 订单 2. 解析购物车list，循环list放入orderId再放入订单详情，计算订单金额 3. 入库订单详情 4.
	 * 订单价格根据数据库内订单详情计算 5. 入库订单 6. 删除购物车 7. 返回订单详情list
	 *
	 * @param param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResponseForm createOrderAndDetailsFromCart(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String wxUid = null;
		String tradeType = (String) paramMap.get("tradeType");
		try {
			Integer userStatus = (Integer) paramMap.get("userStatus");

			// 接收前端购物车json
			List<Map<String, Object>> cartMapList = (List<Map<String, Object>>) paramMap.get("list");

			// 根据前端购物车查询对应数据库购物车信息
			List<Map<String, Object>> cartDbList = cartMapper.getCartListByPrimaryKeys(cartMapList);
			if (cartDbList.size() == 0) {
				throw new Exception();
			}

			// 生成订单号
			String orderId = OrderIdGenerater.generateOrderId();

			wxUid = (String) cartMapList.get(0).get("wxUid");
			String storeNo = (String) cartMapList.get(0).get("storeNo");
			String activityId = (String) cartMapList.get(0).get("activityId");
			int orderGoodsNum = 0;
			BigDecimal orderPrice = BigDecimal.ZERO;
			// 解析购物车list，循环list放入orderId再放入订单详情，计算订单金额
			for (Map<String, Object> map : cartDbList) {
				map.put("orderId", orderId);
				orderGoodsNum = (int) map.get("goodsNum") + orderGoodsNum;
				BigDecimal num = new BigDecimal((int) map.get("goodsNum"));
				BigDecimal price = new BigDecimal(String.valueOf(map.get("goodsPrice")));
				orderPrice = (price.multiply(num)).add(orderPrice);
				// 删除购物车
				cartMapper.bakCarts(map);
				cartMapper.deleteCart(map);
			}

			Map<String, Object> userAddressIdAndPostage = orderMapper.getUserAddressIdAndPostageByWxUid(wxUid, storeNo);
			// 组装订单
			HashMap<String, Object> orderMap = new HashMap<>();
			orderMap.put("id", orderId);
			orderMap.put("wxUid", wxUid);
			orderMap.put("price", orderPrice);
			orderMap.put("goodsNum", orderGoodsNum);
			orderMap.put("storeNo", storeNo);
			orderMap.put("postage", userAddressIdAndPostage.get("postage"));
			orderMap.put("userAddressId", userAddressIdAndPostage.get("userAddressId"));
			orderMap.put("activityId", activityId);
			orderMap.put("tradeType", tradeType);
			if("APP".equals(tradeType)) {
				orderMap.put("appUid", wxUid);
			}
			// 订单和详情入库
			orderMapper.createOrder(orderMap);
			log.info("订单入库,订单号={}", orderId);
			orderMapper.createOrderDetails(cartDbList);
			log.info("订单详情入库");

			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("orderId", orderId);
			dataMap.put("orderPrice", String.valueOf(orderPrice));
			dataMap.put("orderGoodsNum", String.valueOf(orderGoodsNum));
			result.setData(dataMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("购物车生成订单error,wxUid=" + wxUid, e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@SuppressWarnings({ "unused", "rawtypes" })
	public ResponseForm addGiftPackOrder(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String wxUid = (String) paramMap.get("wxUid");
			String storeNo = (String) paramMap.get("storeNo");
			Integer goodsId = (Integer) paramMap.get("goodsId");
			Integer userAddressId = (Integer) paramMap.get("userAddressId");
			String detailedAddress = (String) paramMap.get("detailedAddress");
			String tradeType = (String) paramMap.get("tradeType");
			String contacts = (String) paramMap.get("contacts");
			String mobilePhone = (String) paramMap.get("mobilePhone");
			Date now = new Date();
			String orderType = "2";
			String orderId = OrderIdGenerater.generateOrderId();// 生成订单号
			if (StringUtils.isBlank(wxUid) || StringUtils.isBlank(goodsId.toString())
					|| StringUtils.isBlank(detailedAddress) || StringUtils.isBlank(tradeType)
					|| StringUtils.isBlank(contacts) || StringUtils.isBlank(mobilePhone)
					|| StringUtils.isBlank(storeNo)) {
				result.fail("400", "缺少必要参数");
				return result;
			}
			try {
				Goods giftPackInfo = goodsMapper.selectByPrimaryKey(goodsId);
				/* 组装订单 */
				HashMap<String, Object> orderMap = new HashMap<>();
				orderMap.put("id", orderId);
				orderMap.put("wxUid", wxUid);
				orderMap.put("price", giftPackInfo.getGoodsPrice());
				orderMap.put("goodsNum", 1);
				orderMap.put("storeNo", storeNo);
				orderMap.put("postage", 0);
				orderMap.put("userAddressId", userAddressId);
				orderMap.put("detailedAddress", detailedAddress);
				orderMap.put("orderType", orderType);
				orderMap.put("tradeType", tradeType);
				orderMap.put("contacts", contacts);
				orderMap.put("mobilePhone", mobilePhone);
				orderMap.put("createTime", now);
				orderMap.put("updateTime", now);
				orderMap.put("expireTime", add30Minutes(now));
				orderMap.put("isDelete", 0);
				orderMap.put("orderStatus", "W");
				orderMap.put("logisticStatus", "LW");
				orderMapper.addGiftPackOrder(orderMap);
				
				/*组装订单详情*/
				HashMap<String, Object> detailMap = new HashMap<>();
				detailMap.put("orderId", orderId);
				detailMap.put("goodsName", giftPackInfo.getGoodsName());
				detailMap.put("goodsPic", giftPackInfo.getGoodsPic());
				detailMap.put("goodsNum", 1);
				detailMap.put("goodsPrice", giftPackInfo.getGoodsPrice());
				detailMap.put("originalPrice", giftPackInfo.getGoodsPrice());
				detailMap.put("goodsId",  giftPackInfo.getGoodsId());
				orderMapper.addGiftPackOrderDetails(detailMap);
				
				Map<String, Object> dataMap = new HashMap<>();
				dataMap.put("orderId", orderId);
				dataMap.put("orderPrice", giftPackInfo.getGoodsPrice());
				
				result.succ("操作成功", dataMap);
			} catch (Exception e) {
				e.printStackTrace();
				result.fail("400", "参数错误");
			}
		} else {
			result.fail("400", "参数错误");
		}
		return result;
	}
	@SuppressWarnings("rawtypes")
	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResponseForm rechargeMemberOrder(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String wxUid = (String) paramMap.get("wxUid");
			String storeNo = (String) paramMap.get("storeNo");
			// Integer goodsId = (Integer) paramMap.get("goodsId");
			// Integer userAddressId = (Integer) paramMap.get("userAddressId");
			// String detailedAddress = (String) paramMap.get("detailedAddress");
			String tradeType = (String) paramMap.get("tradeType");
			// String contacts = (String) paramMap.get("contacts");
			// String mobilePhone = (String) paramMap.get("mobilePhone");
			 String refereeMobile = (String) paramMap.get("refereeMobile");//购买88会员的订单时携带推荐人手机号
			Date now = new Date();
			String orderType = "3";/* 2:399礼包订单 3:充值会员订单 */
			String orderId = OrderIdGenerater.generateOrderId();// 生成订单号
			if (StringUtils.isBlank(wxUid) || StringUtils.isBlank(tradeType)||StringUtils.isBlank(storeNo)) {
				result.fail("400", "缺少必要参数");
				return result;
			}
			try {

				Goods memberGoods = new Goods();
				memberGoods.setGiftPack(2);
				memberGoods = goodsMapper.selectOne(memberGoods);
				
				//获取推荐人信息
				String parentWxuid = wxUid;
				if(refereeMobile!=null&&!"".equals(refereeMobile))//推荐人手机号非空，自然流量的推荐人手机为空
				{
					WxUser parm = new WxUser();
					parm.setVerifyPhone(refereeMobile);
					WxUser referee = wxUserMapper.selectOne(parm);
					if(referee!=null)
						parentWxuid = referee.getWxUid();
				}
				/* 组装订单 */
				HashMap<String, Object> orderMap = new HashMap<>();
				orderMap.put("id", orderId);
				orderMap.put("wxUid", wxUid);
				orderMap.put("price", memberGoods.getGoodsPrice());
				orderMap.put("goodsNum", 1);
				orderMap.put("storeNo", storeNo);
				orderMap.put("postage", 0);
				// orderMap.put("userAddressId", userAddressId);
				// orderMap.put("detailedAddress", detailedAddress);
				orderMap.put("orderType", orderType);
				orderMap.put("tradeType", tradeType);
				// orderMap.put("contacts", contacts);
				// orderMap.put("mobilePhone", mobilePhone);
				orderMap.put("createTime", now);
				orderMap.put("updateTime", now);
				orderMap.put("expireTime", add30Minutes(now));
				orderMap.put("isDelete", 0);
				orderMap.put("orderStatus", "W");
				orderMap.put("logisticStatus", "LW");
				orderMap.put("parentWxUid", parentWxuid);
				orderMapper.addGiftPackOrder(orderMap);

				/* 组装订单详情 */
				HashMap<String, Object> detailMap = new HashMap<>();
				detailMap.put("orderId", orderId);
				detailMap.put("goodsName", memberGoods.getGoodsName());
				detailMap.put("goodsPic", memberGoods.getGoodsPic());
				detailMap.put("goodsNum", 1);
				detailMap.put("goodsPrice", memberGoods.getGoodsPrice());
				detailMap.put("originalPrice", memberGoods.getGoodsPrice());
				detailMap.put("goodsId", memberGoods.getGoodsId());
				orderMapper.addGiftPackOrderDetails(detailMap);

				Map<String, Object> dataMap = new HashMap<>();
				dataMap.put("orderId", orderId);
				dataMap.put("orderPrice", memberGoods.getGoodsPrice());

				result.succ("操作成功", dataMap);
			} catch (Exception e) {
				e.printStackTrace();
				result.fail("400", "参数错误");
			}
		} else {
			result.fail("400", "参数错误");
		}
		return result;
	}

	/* 当前时间+30分钟 */
	private Date add30Minutes(Date now) {
		long millisecond = now.getTime();
		millisecond += 30 * 60 * 1000;
		return new Date(millisecond);
	}

	/**
	 * 立即抢购
	 * <p>
	 * 1. 商品 -> 订单 2. 查询商品信息 -> 订单详情，计算订单金额 3. 入库订单详情 4. 订单价格根据数据库内订单详情计算 5. 入库订单 7.
	 * 返回订单详情list
	 *
	 * @param param
	 * @return
	 */
	@Override
	public ResponseForm createOrderAndDetailsRightNow(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String wxUid = null;
		String tradeType = (String) paramMap.get("tradeType");
		try {
			wxUid = (String) paramMap.get("wxUid");
			Integer userStatus = (Integer) paramMap.get("userStatus");
			String storeNo = (String) paramMap.get("storeNo");
			String goodsId = (String) paramMap.get("goodsId");
			String goodsNum = (String) paramMap.get("goodsNum");
			String goodsPrice = (String) paramMap.get("goodsPrice");
			String specsName = (String) paramMap.get("specsName");
			String goodsPic = (String) paramMap.get("goodsPic");
			String goodsName = (String) paramMap.get("goodsName");
			String goodsColor = (String) paramMap.get("goodsColor");
			String activityId = (String) paramMap.get("activityId");
			if (!StringUtils.isNotBlank(wxUid) || !StringUtils.isNotBlank(storeNo) || !StringUtils.isNotBlank(goodsId)
					|| !StringUtils.isNotBlank(goodsNum) || !StringUtils.isNotBlank(goodsPrice)
					|| !StringUtils.isNotBlank(specsName) || !StringUtils.isNotBlank(goodsName)
					|| !StringUtils.isNotBlank(goodsColor) || !StringUtils.isNotBlank(goodsPic)
					|| !StringUtils.isNotBlank(activityId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			// 生成订单号
			String orderId = OrderIdGenerater.generateOrderId();

			// 获取商品详情
			Goods goods = new Goods();
			goods.setGoodsId(Integer.valueOf(goodsId));
			goods = goodsMapper.selectOne(goods);
			HashMap<String, Object> detailMap = new HashMap<>();
			detailMap.put("orderId", orderId);
			detailMap.put("goodsName", goods.getGoodsName());
			detailMap.put("goodsPic", goods.getGoodsPic());
			detailMap.put("goodsNum", goodsNum);
			/* 判断是否为会员 是会员按且当前商品有会员价,按会员价支付,无会员价按折扣价支付,普通用户按折扣价支付 */
			if (!userStatus.equals(0) && goods.getMemberPrice() != null) {
				detailMap.put("goodsPrice", goods.getMemberPrice());
			} else {
				detailMap.put("goodsPrice", goods.getDiscountPrice());
			}
			// detailMap.put("goodsPrice", goods.getDiscountPrice());
			detailMap.put("originalPrice", goods.getGoodsPrice());
			detailMap.put("memberPrice", goods.getMemberPrice());
			detailMap.put("goodsId", goods.getGoodsId());
			detailMap.put("specsName", specsName);
			List<Map<String, Object>> detailList = new ArrayList<>();
			detailList.add(detailMap);

			/* 判断是否为会员 是会员按且当前商品有会员价,按会员价支付,无会员价按折扣价支付,普通用户按折扣价支付 */
			BigDecimal orderPrice = null;
			if (!userStatus.equals(0) && goods.getMemberPrice() != null) {
				orderPrice = goods.getMemberPrice().multiply(new BigDecimal(goodsNum));
			} else {
				orderPrice = goods.getDiscountPrice().multiply(new BigDecimal(goodsNum));
			}

			Map<String, Object> userAddressIdAndPostage = orderMapper.getUserAddressIdAndPostageByWxUid(wxUid, storeNo);
			// 组装订单
			HashMap<String, Object> orderMap = new HashMap<>();
			orderMap.put("id", orderId);
			orderMap.put("wxUid", wxUid);
			orderMap.put("price", orderPrice);
			orderMap.put("goodsNum", goodsNum);
			orderMap.put("storeNo", storeNo);
			orderMap.put("postage", userAddressIdAndPostage.get("postage"));
			orderMap.put("userAddressId", userAddressIdAndPostage.get("userAddressId"));
			orderMap.put("activityId", activityId);
			orderMap.put("tradeType", tradeType);
			if("APP".equals(tradeType)) {
				orderMap.put("appUid", wxUid);
			}
			// 订单和详情入库
			orderMapper.createOrder(orderMap);
			log.info("订单入库,订单号={}", orderId);
			orderMapper.createOrderDetails(detailList);
			log.info("订单详情入库");

			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("orderId", orderId);
			dataMap.put("orderPrice", String.valueOf(orderPrice));
			dataMap.put("orderGoodsNum", goodsNum);
			result.setData(dataMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("立即抢购error,wxUid=" + wxUid, e);
		}
		return result;
	}

	@Override
	public ResponseForm getOrderCountByUserId(RequestForm param) {

		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String wxUid = null;
		try {
			wxUid = (String) paramMap.get("wxUid");
			if (!StringUtils.isNotBlank(wxUid)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			// 获取不同状态订单数量
			Map<String, Object> count = orderMapper.getOrderCountByWxUid(wxUid);

			Map<Object, Object> resultMap = new HashMap<>();
			resultMap.put("allCount", count.get("allCount"));
			resultMap.put("waitPayCount", count.get("waitPayCount"));
			resultMap.put("logicWaitCount", count.get("logicWaitCount"));
			resultMap.put("logicUnderCount", count.get("logicUnderCount"));
			result.setData(resultMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取不同状态订单的数量error,wxUid=" + wxUid, e);
		}
		return result;

	}

	@Override
	public synchronized ResponseForm updateOrderLogisticStatus(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			String logisticStatus = (String) paramMap.get("logisticStatus");
			if (!StringUtils.isNotBlank(orderId) || !StringUtils.isNotBlank(logisticStatus)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			orderMapper.updateOrderStatusById(paramMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("修改订单发货状态error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm updateDetailRefundFlag(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderDetailsId = null;
		try {
			orderDetailsId = (String) paramMap.get("orderDetailsId");
			String refundFlag = (String) paramMap.get("refundFlag");
			if (!StringUtils.isNotBlank(orderDetailsId) || !StringUtils.isNotBlank(refundFlag)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			orderMapper.updateDetailRefundFlagByDetailsId(paramMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("修改详情退款标识状态error,orderDetailsId=" + orderDetailsId, e);
		}
		return result;
	}

	@Override
	public ResponseForm listForManage(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String storeNo = null;
		try {
			String roleId = (String) paramMap.get("roleId");
			storeNo = (String) paramMap.get("storeNo");

			if ("2".equals(roleId)) {
				paramMap.remove("storeNo");
			}

			// 获取订单列表
			com.purchase.util.Page.parsePage(paramMap);
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			List<Map<String, Object>> list = orderMapper.getOrderByStatusAndStoreNo(paramMap);
			// 加优惠券
			for (Map<String, Object> map : list) {
				// 如果有关联优惠券则显示优惠金额
				Coupon coupon = couponMapper.getCouponByOrderId(String.valueOf(map.get("id")));
				if (coupon != null) {
					map.put("couponId", coupon.getId());
					map.put("couponAmount", coupon.getCouponAmount());
				}
			}
			result.setTotal((int) pageHelper.getTotal());
			result.setData(list);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取后台订单列表error,storeNo=" + storeNo, e);
		}
		return result;
	}

	@Override
	public ResponseForm createLogistics(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			String logisticsName = (String) paramMap.get("logisticsName");
			String logisticsNo = (String) paramMap.get("logisticsNo");
			if (!StringUtils.isNotBlank(orderId) || !StringUtils.isNotBlank(logisticsName)
					|| !StringUtils.isNotBlank(logisticsNo)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			orderMapper.insertLogistics(paramMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("添加订单物流信息error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm getLogistics(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			if (!StringUtils.isNotBlank(orderId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			Map<String, Object> map = orderMapper.getLogistics(paramMap);
			result.setData(map);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取订单物流信息error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm reduceGoodsStock(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			if (!StringUtils.isNotBlank(orderId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			// 根据订单id查订单详情
			List<Map<String, Object>> detailList = orderMapper.getOrderDetailListByOrderId(orderId);
			for (Map<String, Object> detailMap : detailList) {
				int stockNum = (int) detailMap.get("stock_num");
				int goodsNum = (int) detailMap.get("goods_num");
				int goodsId = (int) detailMap.get("goods_id");
				String specsName = (String) detailMap.get("specs_name");

				// 更新商品库存
				GoodsStock goodsStock = new GoodsStock();
				goodsStock.setStockNum(stockNum - goodsNum);
				Example example = new Example(GoodsStock.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("goodsId", goodsId);
				criteria.andEqualTo("specsName", specsName);
				goodsStockMapper.updateByExampleSelective(goodsStock, example);
			}
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("减库存error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm cancelOrder(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			if (!StringUtils.isNotBlank(orderId)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			orderMapper.cancelOrder(paramMap);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("取消订单error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm updateOrderRedAddress(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			orderId = (String) paramMap.get("orderId");
			String contacts = (String) paramMap.get("contacts");
			String mobilePhone = (String) paramMap.get("mobilePhone");
			String detailedAddress = (String) paramMap.get("detailedAddress");
			if (!StringUtils.isNotBlank(orderId) || !StringUtils.isNotBlank(contacts)
					|| !StringUtils.isNotBlank(mobilePhone) || !StringUtils.isNotBlank(detailedAddress)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}

			orderMapper.saveOrderAddress(orderId, contacts, mobilePhone, detailedAddress);
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("更新订单冗余地址error,orderId=" + orderId, e);
		}
		return result;
	}

	@Override
	public ResponseForm orderForManage(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String orderId = null;
		try {
			com.purchase.util.Page.parsePage(paramMap);
			Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
			orderId = (String) paramMap.get("orderId");
			List<Map<String, Object>> orders = orderMapper.getOrdersByFuzzyId(orderId);
			result.setData(orders);
			result.setTotal((int) pageHelper.getTotal());
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage(LogInfo.ERROR);
			log.error("获取订单信息error,orderId=" + orderId, e);
		}
		return result;
	}

	/**
	 * 时间戳转换成日期格式字符串
	 *
	 * @param seconds
	 *            精确到秒的字符串
	 * @return
	 */
	private String t2d(Timestamp seconds) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(seconds);
	}

//	@Override
//	public ResponseForm getMemberCouponsInfo(RequestForm param) {
//		ResponseForm result = new ResponseForm();
//		if(param.getData()!=null) {
//			Map paramMap = (Map) param.getData();
//			String wxUid = (String) paramMap.get("wxUid");
//			try {
//				MemberCoupons memberCoupons = memberCouponsMapper.selectByPrimaryKey(wxUid);
//				result.succ("操作成功", memberCoupons);
//			} catch (Exception e) {
//				result.fail("400", "数据获取失败");
//				e.printStackTrace();
//			}
//		}else{
//			result.fail("400", "参数不为空");
//		}
//		return result;
//	}

}
